<template>
<!-- 只有 list 在可视范围内才会检查滚动位置触发 onLoad -->
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error="error"
    error-text="加载失败,请点击重试"
    @load="onLoad"
    :immediate-check="false"
  >

    <CommentItem
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @reply-click="$emit('reply-click', $event)"
    />
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'
export default {
  name: 'CommentList',
  components: { CommentItem },
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      validator (value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  data () {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null, // 获取下一页的标记
      limit: 10,
      error: false
    }
  },
  created () {
    // 所以要手动开启初始 loading
    this.loading = true
    this.onLoad()
  },
  methods: {
    async onLoad () {
      // 请求获取数据
      // 将数据添加到列表中
      // 将loading设置为FALSE
      // 判断是否还有数据
      // 有就更新获取下一页数据页码
      // 没有就将finished设置结束
      try {
        // 获取文章的评论和获取评论的回复是同一个接口
        const { data } = await getComments({
          type: this.type,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit
        })
        const { results } = data.data
        this.list.push(...results)
        // 把文章的总数量传递到外部
        this.$emit('onload-success', data.data)
        this.loading = false
        if (results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (error) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less">

</style>
